/*
 * =====================================================================================
 *
 *       Filename:  ipconverter.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  01/08/2012 11:02:12 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  gnuhpc (http://blog.csdn.net/gnuhpc), warmbupt@gmail.com
 *        Company:  CMBC
 *
 * =====================================================================================
 */
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;


char* itoa(int i)
{
	char* temp = new char(6);
	sprintf(temp,"%d",i);
	return temp;
}

char* numToIP1(unsigned int num)
{
	char* buf = new char[sizeof("aaa.bbb.ccc.ddd")];
	unsigned char* p = (unsigned char *)&num;
	sprintf(buf, "%d.%d.%d.%d", p[3]&0xff,p[2]&0xff,p[1]&0xff,p[0]&0xff);
	return buf;
}
char* numToIP2(unsigned int num)
{
	char* buf = new char[sizeof("aaa.bbb.ccc.ddd")];
	for(int i=3;i>=0;i--)
	{
		strcat(buf, itoa((num>>8*i)&0xff));
		if(i!=0)
			strcat(buf,".");
	}

	return buf;
}

unsigned int ipToNum(char* ip)
{
	char* p;
	int sections[4]={0};
	int i=0;

	p = strtok(ip,".");
	while( p )
	{
		sections[i] = atoi(p);
		p = strtok(NULL,".");
		cout << sections[i] << endl;
		i++;
	}

	unsigned int num =0;
	for( int j=3,i=0 ; j>=0 ; j--,i++ )
	{
		num += (sections[i] <<(8*j));
	}
	
	return num;
}

int main(){
	char* p = numToIP1(167773121);
	cout << p << endl;
	delete p;

	p = numToIP2(167773121);
	cout << p << endl;
	delete p;


	char ip[16] = "10.0.3.193";
	cout << ipToNum(ip) << endl;
	return 0;
}
